<template>
  <n-card style="width: 600px" :title="$t('user.profile.editor.title')" :bordered="false" size="huge" role="dialog"
    aria-modal="true">
    <n-form ref="form">
      <n-form-item :label="$t('user.profile.overview.username')" required>
        <n-input v-model:value="model.username"></n-input>
      </n-form-item>
      <n-form-item :label="$t('user.profile.overview.email')" required>
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-input v-model:value="model.email" disabled></n-input>
          </template>
          {{ $t("user.profile.editor.messages.edit-email") }}
        </n-tooltip>
      </n-form-item>
      <n-form-item :label="$t('user.profile.overview.profile')">
        <n-input v-model:value="model.profile" type="textarea"></n-input>
      </n-form-item>
      <n-button :loading="pushing" style="width: 100%" type="primary" @click="submit">
        {{ $t("common.actions.update") }} 
      </n-button>
    </n-form>
  </n-card>
</template>

<script setup>
import axiosHttp from "axios";
import { NCard, NForm, NFormItem, NInput, NButton, NTooltip, useMessage } from "naive-ui";
import { onMounted, reactive, ref, defineEmits } from "vue";
import { useI18n } from "vue-i18n";
import { useCookies } from "vue3-cookies";
import { useStore } from "../../../stores/main";

const { t } = useI18n();
const { cookies } = useCookies();
const message = useMessage();
const axios = axiosHttp.create({ validateStatus: () => true });
const store = useStore();
const emit = defineEmits(["reload", "close"]);

const pushing = ref(false);
const form = ref(null);
const model = reactive({
  username: "",
  email: "",
  profile: "",
});

onMounted(() => {
  model.username = store.account.accountProfile.username;
  model.email = store.account.accountProfile.email;
  model.profile = JSON.stringify(store.account.accountProfile.profile, null, 4);
});

function submit() {
  form.value?.validate((error) => {
    if (!error) {
      let profile;
      try {
        profile = JSON.parse(model.profile);
      } catch (e) {
        message.error("Failed to update profile, your profile scheme is error!")
        return;
      }

      pushing.value = true;
      axios
        .patch("/api/management/users",
          {
            username: model.username,
            email: model.email,
            profile: profile,
          },
          {
            headers: { Authorization: "Bearer " + cookies.get("access_token") }
          })
        .catch(() => {
          message.error(t("common.message.request-unknown-error"));
          pushing.value = false;
        })
        .then((response) => {
          if (response.status === 200) {
            message.success(t("user.profile.editor.messages.success"));
            emit("reload");
            emit("close");
          } else {
            message.error(t("common.messages.request-unknown-error"));
            console.error("Request error: ", response);
          }
          pushing.value = false;
        });
    }
  });
}
</script>
